<template>
  <el-form :model="dataForm" :rules="rules" label-position="top" class="form-box" ref="dataFormRef"
    @keyup.enter="dataFormSubmitHandle()" label-width="120px">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="deptId" label="研学基地名称">
          <el-select v-model="dataForm.deptId" clearable placeholder="请选择">
            <el-option :value="item.id" :label="item.name" v-for="(item, index) in deptList"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="username" label="账号名">
          <el-input v-model="dataForm.username" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="managerName" label="基地责任人姓名">
          <el-input v-model="dataForm.managerName" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="managerTel" label="责任人联系电话">
          <el-input v-model="dataForm.managerTel" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="managerInfo" label="责任人身份信息">
          <el-input v-model="dataForm.managerInfo" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="status" label="账号状态">
          <el-select v-model="dataForm.status" clearable placeholder="请选择">
            <el-option :value="1" label="启用"></el-option>
            <el-option :value="0" label="停用"></el-option>
          </el-select>
        </el-form-item></el-col>
    </el-row>
    <el-form-item class="footer-btn">
      <el-button @click="cancelHandle()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const row: any = JSON.parse(route.query?.row as string || '{}');
const dataFormRef = ref();
const deptList = ref<any[]>([]);
const roleList = ref([]);

const dataForm = reactive({
  id: "",
  deptId: "",
  deptType: "BASE",
  username: "",
  managerName: "",
  managerTel: "",
  managerInfo: "",
  status: 0,
  type: "BASE",
});

const rules = ref({
  deptId: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  username: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
});

const init = () => {
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getDeptList(), getRoleList()]).then(() => {
    if (row?.id) {
    Object.assign(dataForm, row);
  }
  });
};

// 获取基地列表
const getDeptList = () => {
  return baseService.get("/study/dept/page", { type: 'BASE' }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    deptList.value = res.data.list;
  });
};

// 获取角色列表
const getRoleList = () => {
  return baseService.get("sys/role/list", { }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    roleList.value = res.data;
  });
};

const updateUserInfo = (id: string) => {
  if (!id) return;
  const roleIdList = roleList.value.filter((k: any) => k.name.includes('基地')).map((d: any)=> d.id);

  baseService.get(`/sys/user/${id}`).then((res) => {
    if (res.code === 0) {
      baseService.put(`/sys/user`, {...res.data, roleIdList: [...new Set(roleIdList.concat(res.data.roleIdList))]});
    }
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    baseService.post(`/study/user/${!dataForm.id ? 'save' : 'update'}`, dataForm).then((res) => {
      updateUserInfo(res.data);
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          router.push('/study/base-user');
        }
      });
    });
  });
};

const cancelHandle = () => {
  router.go(-1);
};

onMounted(() => {
  init();
  getDeptList();
})
</script>
